//app.js
var Utils = require('/utils/util.js');
App({
    globalData: {
        host: Utils.Host,
        Rule: Utils.Rule,
        appid: Utils.FootConvenientService.appid,
        path: Utils.FootConvenientService.path,
        envVersion: Utils.FootConvenientService.envVersion,
        orderType: 10,
        bizDoingFlag: "1",
        bizFinishFlag: "2",
        bizAllFlag: "3",
        userInfo: null,
        isAuthSuccess:false,
        openId: "",
        channelId: "",
        carYueS: "粤S",
        cacheAddressKey: "CACHE_ADDRESS_KEY",
        cachePageKey: "CACHE_PAGE_KEY",
        cacheOrderResKey: "CACHE_ORDER_RES_KEY",
        cacheWxOpenIdKey: "CACHE_WX_OPENID_KEY",
        cardPictureKey: "CARD_PICTURE_KEY",
        policyPictureKey: "POLICY_PICTURE_KEY"
    },
    onLaunch: function () {
        this.getUserInfo();
    },
    //跨小程序跳转
    crossToUrl: function (res) {
        if (wx.navigateToMiniProgram) {
            wx.navigateToMiniProgram({
                appId: res.appid,
                path: res.path,
                envVersion: res.envVersion,
                success: function (data) {
                    console.log('跳转成功', data)
                },
                fail: function (data) {
                    console.log('跳转失败', data)
                }
            })
        } else {
            // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
            wx.showModal({
                title: '提示',
                content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            })
        }
    },
    toastAuthFailModal: function () {
        wx.showModal({
            title: '微信认证失败',
            content: '请退出“邮证车辆年检”，然后再次进入，重新获取微信认证。',
            showCancel: false,
            success: function (res) {
                if (res.confirm) {
                    console.log('用户点击确定');
                } else if (res.cancel) {
                    console.log('用户点击取消');
                }
            }
        });
    },
    getUserInfo: function (cb) {
        var that = this;
        if (this.globalData.userInfo) {
            typeof cb == "function" && cb(this.globalData.userInfo)
        } else {
            wx.login({//调用登录接口
                success: function (res) {
                    wx.getUserInfo({
                        success: function (result) {
                            that.globalData.userInfo = result.userInfo;
                            that.globalData.userInfo['code'] = res.code;
                            var opt = {///授权成功，更新用户信息
                                url: that.globalData.host + "/wx/an/uwu.ajax",
                                data: that.globalData.userInfo,
                                showLoadFlag: "false",
                                sucFn: function (data) {
                                }
                            };
                            that.ajax(opt);
                            typeof cb == "function" && cb(that.globalData.userInfo);
                        },
                        fail: function (result) {
                            var userObj = {
                                "avatarUrl": "https://yzres.oss-cn-shenzhen.aliyuncs.com/wx/images/common/mine_default_heard@2x.png",
                                "nickName": "游客"
                            };
                            that.globalData.userInfo = userObj;
                            wx.showModal({
                                title: '微信授权失败',
                                content: '请先在小程序列表完全删除“邮证车辆年检”，然后通过扫描二维码或在小程序中搜索“邮证车辆年检”再次进入，允许小程序获取您的用户信息。',
                                showCancel: false,
                                success: function (res) {
                                    if (res.confirm) {
                                        console.log('用户点击确定');
                                    } else if (res.cancel) {
                                        console.log('用户点击取消');
                                    }
                                }
                            });
                        }
                    })
                }
            })
        }
    },
    makePhoneCall: function (phone) {
        wx.makePhoneCall({
            phoneNumber: phone
        });
    },
    toYMDHMSDate: function (number) {
        return Utils.toYMDHMSDate(number);
    },
    toYMDDate: function (number) {
        return Utils.toYMDDate(number);
    },
    toast: function (mes, icon) {
        Utils.toast(mes, icon);
    },
    ajax: function (opt) {
        var that = this;
        opt['pageObj'] = this.getCurrentPage();
        opt.data['WX_OPENID'] = this.globalData.openId;
        opt.data['WX_CHANNEL'] = this.globalData.channelId||'';
        opt['accountIdBlankFn'] = function () {
            Utils.errorToast(that.getCurrentPage(), "网络错误，刷新试试");
            that.globalData.openId = "";
            that.globalData.isAuthSuccess = false;
        };
        Utils.ajax(opt);
    },
    errorToast: function (mes) {
        Utils.errorToast(this.getCurrentPage(), mes);
    },
    hidePopErrorMes: function () {
        Utils.hidePopErrorMes(this.getCurrentPage());
    },
    check: function (jsonArray) {
        return Utils.check(jsonArray, this.getCurrentPage());
    },
    initAddress: function () {
        Utils.initAddress(this.getCurrentPage());
    },
    bindAddressChange: function (e) {
        Utils.bindAddressChange(e, this.getCurrentPage());
    },
    /**封装微信的方法,统一入口，方便后续做统一的处理**/
    navigateTo: function (data) {
        wx.navigateTo({
            url: data.url,
            success: function (res) {
                if (!(data.success == null || data.success == "" || typeof (data.success) == "undefined")) {
                    data.success(res);
                }
            },
            fail: function () {
                if (!(data.fail == null || data.fail == "" || typeof (data.fail) == "undefined")) {
                    data.fail(res);
                }
            },
            complete: function () {
                if (!(data.complete == null || data.complete == "" || typeof (data.complete) == "undefined")) {
                    data.complete(res);
                }
            }
        })
    },
    redirectTo: function (data) {
        wx.redirectTo({
            url: data.url,
            success: function (res) {
                if (!(data.success == null || data.success == "" || typeof (data.success) == "undefined")) {
                    data.success(res);
                }
            },
            fail: function () {
                if (!(data.fail == null || data.fail == "" || typeof (data.fail) == "undefined")) {
                    data.fail(res);
                }
            },
            complete: function () {
                if (!(data.complete == null || data.complete == "" || typeof (data.complete) == "undefined")) {
                    data.complete(res);
                }
            }
        })
    },
    getStorageSync: function (key) {
        return wx.getStorageSync(key);
    },
    setStorageSync: function (key, value) {
        wx.setStorageSync(key, value);
    },
    removeStorageSync: function (key) {
        try {
            wx.removeStorageSync(key)
        } catch (e) {
            // Do something when catch error
        }
    },
    removeStorage: function (key) {
        wx.removeStorage({ key: key, success: function (res) { } });
    },
    identityCodeValid: function (code) {
        var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " };
        var tip = "";
        var pass = true;

        if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
            tip = "身份证号格式错误";
            pass = false;
        }

        else if (!city[code.substr(0, 2)]) {
            tip = "地址编码错误";
            pass = false;
        }
        else {
            //18位身份证需要验证最后一位校验位
            if (code.length == 18) {
                code = code.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                //校验位
                var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++) {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                var last = parity[sum % 11];
                if (parity[sum % 11] != code[17]) {
                    tip = "校验位错误";
                    pass = false;
                }
            }
        }
        return pass;
    },
    isAndroid: function () {
        var res = wx.getSystemInfoSync()
        if (res.model.indexOf('iPhone') > -1) {
            return false;
        } else {
            return true;
        }
    },
    isYueS: function (carNumPrefix,cityId) {
        return false;
        if (carNumPrefix == this.globalData.carYueS&&cityId=='441900') {
            return true;
        } else {
            return false;
        }
    },
    requestPayment: function (opt) {
        Utils.requestPayment(opt);
    },
    chooseImage: function (opt) {
        wx.chooseImage({
            count: opt.count, // 默认9
            sizeType: opt.sizeType, // 可以指定是原图还是压缩图，默认二者都有
            sourceType: opt.sourceType, // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                if (!(opt.success == null || opt.success == "" || typeof (opt.success) == "undefined")) {
                    opt.success(res);
                }
            },
            fail: function (res) {
                if (!(opt.fail == null || opt.fail == "" || typeof (opt.fail) == "undefined")) {
                    opt.fail(res);
                }
            },
            complete: function (res) {
                console.log(res);
            }
        });
    },
    previewImage: function (opt) {
        wx.previewImage({
            urls: opt.urls, // 默认9
            success: function (res) {
                if (!(opt.success == null || opt.success == "" || typeof (opt.success) == "undefined")) {
                    opt.success(res);
                }
            }
        });
    },
    uploadFile: function (opt) {
        Utils.uploadFile(opt);
    },
    navigateBack: function () {
        wx.navigateBack();
    },
    setNavigationBarTitle: function (title) {
        wx.setNavigationBarTitle({
            title: title
        })
    },
    showModal: function (opt) {
        opt.showCancel = (opt.showCancel == null || opt.showCancel == "" || typeof (opt.showCancel) == "undefined") ? true : false;
        opt.cancelText = (opt.cancelText == null || opt.cancelText == "" || typeof (opt.cancelText) == "undefined") ? "取消" : opt.cancelText;
        opt.confirmText = (opt.confirmText == null || opt.confirmText == "" || typeof (opt.confirmText) == "undefined") ? "确定" : opt.confirmText;
        wx.showModal({
            title: opt.title,
            content: opt.content,
            showCancel: opt.showCancel,
            cancelText: opt.cancelText,
            confirmText: opt.confirmText,
            success: function (res) {
                if (res.confirm) {
                    if (!(opt.success == null || opt.success == "" || typeof (opt.success) == "undefined")) {
                        opt.success();
                    }
                } else if (res.cancel) {
                    if (!(opt.cancel == null || opt.cancel == "" || typeof (opt.cancel) == "undefined")) {
                        opt.cancel();
                    }
                }
            }
        });
    }
});